
import { _decorator, Color, Component, Label, Node, Sprite, Animation, AnimationClip } from 'cc';
import { AppControll, ConfigKey, configKey, EventName, PopView, secondaryGun_config, secondGun_specialSkill_config } from '../manager/AppControll';
import { DataHelper } from '../system/DataHelper';
import { Tools } from '../tools/Tools';
import { Loader } from '../tools/LoadManger';
import { SecondaryGun } from '../fight/gun/SecondaryGun';
import EvtManger from '../tools/EvtManger';
import { GameData, SecondaryGunStruct } from '../system/GameData';
import { PopManager } from '../manager/PopManager';
import { SystemMessage } from './SystemMessage';
import { SoundManager } from '../manager/SoundManger';
import { BuildingPlatform } from './BuildingPlatform';
import { SecondGunChoose } from './SecondGunChoose';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = secondGunUi
 * DateTime = Wed May 17 2023 21:39:52 GMT+0800 (GMT+08:00)
 * Author = guoxun
 * FileBasename = secondGunUi.ts
 * FileBasenameNoExtension = secondGunUi
 * URL = db://assets/script/pop/secondGunUi.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('SecondGunUi')
export class SecondGunUi extends Component {
    @property(Sprite)
    mSpSecndRes: Sprite = null;
    @property(Label)
    mLbSecondGunName: Label = null;
    @property(Label)
    mLbSkillDescription: Label = null;
    @property(Label)
    mLbAtkNum: Label = null;
    @property(Label)
    mLbAttackSpeed: Label = null;
    @property(Label)
    mLbResetCosts: Label = null;
    @property(Label)
    mLbLevel: Label = null;
    @property(Node)
    mNdStar: Node = null;
    @property(Label)
    mGold: Label = null;
    @property(Label)
    mPearls: Label = null;
    @property(Node)
    mNdRandomFree: Node = null;
    @property(Node)
    mNdCoinIcon: Node = null;

    private mConfig: secondGun_specialSkill_config = null;
    private mBody: Node = null;
    private mLevel: number = 1;
    private mCurUnlockId: number = null;
    private mNdLevelUp: Node = null;
    private mStartAn: Node = null;
    private mUpdateCount = 0;
    private mNdMaxTag = null;
    private mNdNormalTag = null;
    private mBuildingPlatform: BuildingPlatform = null
    private mCurGunStruct: SecondaryGunStruct = null;
    private mAlternativeGunStruc: SecondaryGunStruct = null;
    private mIsRandoming = false;
    protected onLoad(): void {
        GameData.isPause = true;
        this.mBody = this.node.getChildByName("body");
        this.mNdLevelUp = this.node.getChildByName("levelUp");
        this.mStartAn = this.mBody.getChildByName("star-ani");
        this.mStartAn.active = false;
        this.mBody.getComponent(Animation).on(Animation.EventType.FINISHED, () => {
            this.mStartAn.active = false;
        })
        this.mNdMaxTag = this.mBody.getChildByName("maxLevel");
        this.mNdNormalTag = this.mBody.getChildByName("levelUpBtn").getChildByName("Label");
        this.mBuildingPlatform = this.mBody.getChildByName("buildingPlatform").getComponent(BuildingPlatform);
        this.RegisterEvents();
        Loader.LoadEffectImageDir(GameData.mainGunlevelUpAn, (arr) => {
            if (!arr) return;
            if (!this.mNdLevelUp) return;
            let an = this.mNdLevelUp.getComponent(Animation);
            if (!an) return;
            const clip = AnimationClip.createWithSpriteFrames(arr, arr.length);
            clip.name = "levelUp";
            clip.wrapMode = AnimationClip.WrapMode.Normal;
            an.addClip(clip);
        })
        this.node.getChildByName("body").getComponent(Animation).on(Animation.EventType.FINISHED, () => {
            PopManager.Instance<PopManager>().ShowPop(PopView.secondGunChoose, node => {
                this.scheduleOnce(() => {
                    this.mIsRandoming = false;
                }, 0.1)
                node.getComponent(SecondGunChoose).InitChoose(this.mCurGunStruct, this.mAlternativeGunStruc, this.mCurUnlockId);
            })
        }, this);
    }

    RegisterEvents() {
        EvtManger.on(EventName.resetGun, this, this.OnResetGun);
    }

    protected onDestroy(): void {
        EvtManger.off(EventName.resetGun, this, this.OnResetGun);
    }

    OnResetGun(id, sct) {
        this.mLevel = sct.level;
        this.mConfig = DataHelper.GetSpecialSkillConfigById(sct.configId);
        this.InitView();
        this.mStartAn.active = true;
    }

    PlayLevelUp() {
        let an = this.mNdLevelUp.getComponent(Animation);
        an.play("levelUp");
    }

    InitSecondGunUi(unlockId: number, config: secondGun_specialSkill_config, level: number) {
        this.mCurUnlockId = unlockId;
        this.mLevel = level;
        this.mConfig = config;
        let sct = Tools.GetNewSecondaryGun();
        this.mCurGunStruct = { level: this.mLevel, configId: this.mConfig.skill };
        this.mAlternativeGunStruc = sct;
        this.InitView();
    }

    InitView() {
        Loader.LoadImage("image/gun/secondaryGun/" + this.mConfig.secondGunTDRes, (spf) => {
            if (this.mSpSecndRes) this.mSpSecndRes.spriteFrame = spf;
        })
        if (!DataHelper.GetSecondaryConfigByLv(this.mLevel + 1)) {
            this.mNdMaxTag.active = true;
            this.mNdNormalTag.active = false;
        } else {
            this.mNdMaxTag.active = false;
            this.mNdNormalTag.active = true;
        }
        this.mBuildingPlatform.InitBuildingPlatform();
        let config: secondaryGun_config = DataHelper.GetSecondaryConfigByLv(this.mLevel);
        this.mLbSecondGunName.string = this.mConfig.secondGunName;
        this.mLbSkillDescription.string = this.mConfig.skillDescribe;
        this.mLbAtkNum.string = (config.aggressivity * DataHelper.GetGunAtkProportionByQuality(this.mConfig.skillQuality)).toFixed(0)
        this.mLbAttackSpeed.string = config.attackSpeed.toFixed(2);
        this.mLbLevel.string = this.mLevel + "";
        this.mLbSecondGunName.color = new Color(DataHelper.GetColorByLv(this.mConfig.skillQuality + 1).value);
        let consume = DataHelper.GetConfigByKey(ConfigKey.randomGunSpend).value;
        this.mLbResetCosts.string = consume;
        if (Number.parseInt(consume) > GameData.playerData.pearls) {
            this.mLbResetCosts.color = Color.RED;
        } else {
            this.mLbResetCosts.color = Color.WHITE;
        }
        let count = 0;
        this.mNdStar.children.forEach(elemt => {
            if (this.mConfig.skillQuality >= count) {
                elemt.active = true;
            } else {
                elemt.active = false;
            }
            count++;
        })

        this.mNdRandomFree.active = false
        this.mNdCoinIcon.active = true;
        if (GameData.playerData.freeRandomCount > 0) {
            this.mNdRandomFree.active = true;
            this.mNdCoinIcon.active = false;
            let str = DataHelper.GetConfigByKey(ConfigKey.freeRandomText).value;
            let value0 = GameData.playerData.freeRandomCount.toString();
            str = str.replace('${value0}', value0);
            this.mNdRandomFree.getComponent(Label).string = str;
        }
    }

    OnBtnClose() {
        GameData.isPause = false;
        AppControll.ShelvedTime = 0;
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        this.node.active = false;
    }

    OnBtnReset() {
        if (this.mIsRandoming) return;
        AppControll.ShelvedTime = 0;
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        this.mIsRandoming = true;
        //在免费次数期间
        if (GameData.playerData.freeRandomCount > 0) {
            this.mNdRandomFree.active = true;
            GameData.playerData.freeRandomCount -= 1;
            if (GameData.playerData.freeRandomCount > 0) {
                let str = DataHelper.GetConfigByKey(ConfigKey.freeRandomText).value;
                let value0 = GameData.playerData.freeRandomCount.toString();
                str = str.replace('${value0}', value0);
                this.mNdRandomFree.getComponent(Label).string = str;
            } else {
                this.mNdRandomFree.active = false;
            }

            let sct = Tools.GetNewSecondaryGun();
            this.mCurGunStruct = { level: this.mLevel, configId: this.mConfig.skill };
            this.mAlternativeGunStruc = sct;
            this.mLevel = sct.level;
            this.mConfig = DataHelper.GetSpecialSkillConfigById(sct.configId);
            this.InitView();
            this.mStartAn.active = true;
            this.node.getChildByName("body").getComponent(Animation).play();
            SoundManager.Instance<SoundManager>().PlayEffect(GameData.getRandom);
            return;
        }
        let price = Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.randomGunSpend).value);
        if (GameData.playerData.pearls >= price) {
            GameData.AddPearls(price * -1);
            let sct = Tools.GetNewSecondaryGun();
            this.mCurGunStruct = { level: this.mLevel, configId: this.mConfig.skill };
            this.mAlternativeGunStruc = sct;
            this.mLevel = sct.level;
            this.mConfig = DataHelper.GetSpecialSkillConfigById(sct.configId);
            this.InitView();
            this.mStartAn.active = true;
            this.node.getChildByName("body").getComponent(Animation).play();
            SoundManager.Instance<SoundManager>().PlayEffect(GameData.getRandom);
        } else {
            PopManager.Instance<PopManager>().ShowPop(PopView.systemMessage, (node) => {
                node.getComponent(SystemMessage).InitContent("钻石不足");
            })
        }
    }

    ShowList() {
        PopManager.Instance<PopManager>().ShowPop(PopView.secondGunList);
    }

    protected update(dt: number): void {
        this.mUpdateCount++;
        if (this.mUpdateCount % 10 == 0) {
            this.mGold.string = Tools.FormatNumber(GameData.playerData.Gold);
            this.mPearls.string = GameData.playerData.pearls + "";
        }
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/zh/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/zh/scripting/life-cycle-callbacks.html
 */
